<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--条件查询-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="群组名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入群组名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="群组类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择群组类型" clearable
                       size="small"
            >
              <el-option
                v-for="dict in statusOptionsType"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['smart:group:query']"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['smart:group:export']"
            >导出
            </el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="groupList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" v-if="false"/>
          <el-table-column label="手机号" align="center" prop="account" width="120"/>
          <el-table-column label="网关MAC" align="center" prop="gatewayMac" :show-overflow-tooltip="true"/>
          <el-table-column label="家庭名称" align="center" prop="homeName" :show-overflow-tooltip="true"/>
          <el-table-column label="群组名称" align="center" prop="name" :show-overflow-tooltip="true"/>
          <el-table-column label="群组类型" align="center" prop="type" v-if="false"/>
          <el-table-column label="群组编号" align="center" prop="code" v-if="false"/>
          <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="180">
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetails(scope.row)"
                v-hasPermi="['smart:group:detail']"
              >详情
              </el-button>
              <!--              <el-button-->
              <!--                size="mini"-->
              <!--                type="text"-->
              <!--                icon="el-icon-delete"-->
              <!--                @click="handleDeal(scope.row)"-->
              <!--                v-hasPermi="['system:group:remove']"-->
              <!--              >执行-->
              <!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-descriptions title="网关信息" v-if="false">

      </el-descriptions>
      <gatewayDetails :row="form.gatewayMac" :column-count="3" v-if="false"></gatewayDetails>
      <el-divider v-if="false"/>
      <el-descriptions title="群组信息" :column=3 contentClassName="my-content" labelClassName="my-label">
        <el-descriptions-item label="群组名称">{{ form.name }}</el-descriptions-item>
        <!--        <el-descriptions-item label="所属网关">{{ form.gatewayMac }}</el-descriptions-item>-->
        <el-descriptions-item label="群组类型">
          <template v-for="dict in statusOptionsType">
            <template v-if="dict.dictValue===form.type">
              <el-tag style="margin-top: -15px">{{ dict.dictLabel }}</el-tag>
            </template>
          </template>

        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.modifyTime }}</el-descriptions-item>
      </el-descriptions>
      <el-divider/>
      <el-descriptions title="关联设备"></el-descriptions>
      <template>
        <el-table v-loading="loading" :data="relationDeviceData">
          <el-table-column prop="deviceName" label="设备名称" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if=" scope.row.deviceName===undefined"><el-tag type="info">设备不存在</el-tag></span>
              <span v-else>{{ scope.row.deviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deviceMac" label="设备MAC" width="180">
          </el-table-column>
          <el-table-column prop="deviceType" label="设备类型" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.deviceType }}</span>
            </template>
          </el-table-column>

          <el-table-column label="类型名称" width="200">
            <template slot-scope="scope">
              <div class="myTagCategoryName" v-if="scope.row.defaultDeviceName">
                {{ scope.row.defaultDeviceName }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGroup,
  getGroup,
  delGroup,
  addGroup,
  updateGroup,
  exportGroup
} from '@/api/system/group'
import { deptTreeSelect } from '@/api/system/dept'

import gatewayDetails from '@/views/components/gateway/details'

export default {
  name: 'Group',
  components: { gatewayDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      statusOptionsType: [{ dictValue: 'light', dictLabel: '灯光类' }, {
        dictValue: 'curtain',
        dictLabel: '窗帘类'
      }, { dictValue: 'rgbw', dictLabel: '多彩灯类' }],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      groupList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gatewayId: undefined,
        gatewayMac: undefined,
        homeId: undefined,
        name: undefined,
        type: undefined,
        code: undefined,
        action: undefined,
        modifyTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        homeId: [
          { required: true, message: '家庭ID不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '群组名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '群组类型不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '群组编号不能为空', trigger: 'blur' }
        ]
      },
      relationDeviceData: []
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msgname
    })
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listGroup(this.queryParams).then(response => {
        this.groupList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        gatewayId: undefined,
        gatewayMac: undefined,
        homeId: undefined,
        name: undefined,
        type: undefined,
        code: undefined,
        action: undefined,
        createTime: undefined,
        modifyTime: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // this.ids = selection.map(item => item.id)
      // this.single = selection.length != 1
      // this.multiple = !selection.length
    },
    // /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加【请填写功能名称】";
    // },
    /** 修改按钮操作 */
    handleDetails(row) {
      this.reset()
      const id = row.id || this.ids
      getGroup(id).then(response => {
        this.form = response.data
        this.relationDeviceData = response.data.deviceList
        this.open = true
        this.title = row.name + '详情'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateGroup(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addGroup(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDeal(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认执行编号为"' + row.name + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delGroup(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportGroup(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectedOrgCode = data.id
      this.queryParams.deptId = data.id
      this.getList()
    },
    /**
     * 数字字符串每隔几位插入一个分隔符
     * @param str
     * @param length
     * @param separator
     * @returns {*}
     */
    strInsert(str, length, separator) {
      if (str == null) {
        return ''
      }
      let reg = new RegExp('\\d{1,' + length + '}', 'g')
      let ma = str.match(reg)
      return ma.join(separator)
    }
  }
}
</script>
